<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 1 ? '新增保单' : '编辑保单'"
    :visible.sync="isShow"
    width="700px"
    @close="reset"
  >
    <el-form
      ref="dataForm"
      class="form"
      :rules="rules"
      :model="temp"
      label-position="right"
      label-width="80px"
    >
      <el-form-item label="客户编号" prop="csmCode">
        <el-input v-model="temp.csmCode" placeholder="请输入">
          <el-button
            v-if="type === 1"
            slot="append"
            class="append-search"
            @click="getCsmCode"
          >获取</el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="客户名称" prop="csmName">
        <el-input v-model="temp.csmName" />
      </el-form-item>
      <el-form-item label="注册电话" prop="csmRgPhone">
        <el-input v-model="temp.csmRgPhone" />
      </el-form-item>

      <el-form-item label="客户类型" prop="csmType">
        <el-select v-model="temp.csmType" placeholder="请选择">
          <el-option
            v-for="(l, i) in cmsType"
            :key="i"
            :label="l.desc"
            :value="l.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item style="width: 100%;" label="所在区域" prop="address">
        <el-cascader
          ref="cascaderRef"
          v-model="temp.address"
          style="width: 100%;"
          :props="addressProps"
          clearable
        />
      </el-form-item>
      <el-form-item style="width: 100%;" label="注册地址" prop="csmRgAddress">
        <el-input v-model="temp.csmRgAddress" style="width: 70%;" />
        <el-input v-model="temp.csmFloor" style="width: 10%;" /> 楼
      </el-form-item>
      <el-form-item label="身份证号" prop="sfzh">
        <el-input v-model="temp.sfzh" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所属机构" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :disabled="type === 2 && rowData.csmId !== 0"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>

      <el-form-item label="客户等级" prop="unCheckQuality">
        <el-select v-model="temp.unCheckQuality" placeholder="请选择">
          <el-option
            v-for="(l, i) in cmsLevel"
            :key="i"
            :value="l.value"
            :label="l.desc"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售人员" prop="salesManName">
        <el-input v-model="temp.salesManName" clearable />
      </el-form-item>
      <el-form-item label="执照编号" prop="cardNo">
        <el-input v-model="temp.cardNo" clearable />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 关闭 </el-button>
      <el-button
        :loading="$loadingPlugin.add || $loadingPlugin.edit"
        type="primary"
        @click="success"
      >
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getCodeNum } from '@/api'
  import { selectAreaCode, pickUpCustomerSava, pickUpCustomerDetail } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'EditorAddDialog',
    props: ['treeData', 'cmsLevel', 'cmsType'],
    data() {
      return {
        isShow: false,
        type: 1, // 1新增 2修改
        temp: {
          csmType: 1, // 客户类型
          csmRgPhone: '', // 注册电话
          csmCode: '', // 客户编号
          csmRgAddress: '', // 注册地址
          sfzh: '', // 身份证号
          csmName: '', // 客户名称
          address: [], // 所在区域
          cardNo: '', // 执照编号
          csmFloor: '1', // 楼层
          unCheckQuality: '', // 客户登记
          salesManName: '', // 销售人员
          orgSNNo: '', // 所属机构
          orgName: '',
          orgId: ''
        },
        rowData: {
          csmId: ''
        },
        addressProps: {
          checkStrictly: true,
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: (value && value.code) || 0 })
              .then((res) => {
                const nodes = res.data.map((item) => ({
                  value: {
                    code: item.areaCode,
                    name: item.areaName
                  },
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        }
      }
    },
    computed: {
      rules() {
        const validatePhone = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入注册电话'))
          } else if (
            !/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(
              value
            )
          ) {
            callback(new Error('请输入正确的电话格式'))
          } else {
            callback()
          }
        }
        const validateIDCard = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入身份证号'))
          } else if (
            !/^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/.test(
              value
            )
          ) {
            callback(new Error('请输入正确的身份证号'))
          } else {
            callback()
          }
        }

        const rules = {
          csmType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
          csmName: [{ required: true, message: '请选择输入客户名称', trigger: 'change' }],
          csmRgPhone: [{ required: true, validator: validatePhone, trigger: 'change' }],
          csmRgAddress: [
            { required: true, message: '请输入注册地址', trigger: 'change' },
            { max: 50, message: '注册地址长度过长', trigger: 'change' }
          ],
          orgSNNo: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
          sfzh: [{ required: true, validator: validateIDCard, trigger: 'change' }],
          cardNo: [{ required: true, message: '请输入营业执照编号', trigger: 'change' }]
        }
        if (this.csmId !== 0) delete rules.sfzh
        if (this.$store.state.user && this.$store.state.user.corpSettingData) {
          const sp5 = this.$store.state.user.corpSettingData.sp5
          if (
            !((sp5 >> 13) & 0x01 && (this.temp.csmType === 2 || this.temp.csmType === 4))
          ) {
            delete rules.cardNo
          }
        }
        return rules
      }
    },
    methods: {
      show(type, row) {
        this.type = type
        this.isShow = true
        if (type === 2) {
          this.init(row)
        }
      },
      async init(row) {
        const { status, data } = await pickUpCustomerDetail({
          csmPickupId: row.csmPickupId
        })
        if (status === 200) {
          let areaText = ''
          for (const key in this.temp) {
            if (key === 'address') {
              const provinceData = {
                code: data.provinceCode,
                name: data.provinceName
              }
              const cityData = {
                code: data.cityCode,
                name: data.cityName
              }
              const countryData = {
                code: data.countryCode,
                name: data.countryName
              }
              const streetData = {
                code: data.streetCode,
                name: data.streetName
              }
              if (data.provinceCode && data.provinceCode !== '000000') {
                this.temp['address'].push(provinceData)
                areaText += provinceData.name
              }

              if (data.cityCode && data.cityCode !== '000000') {
                this.temp['address'].push(cityData)
                areaText += ' / ' + cityData.name
              }

              if (data.countryCode && data.countryCode !== '000000') {
                this.temp['address'].push(countryData)
                areaText += ' / ' + countryData.name
              }

              if (data.streetCode && data.streetCode !== '000000') {
                this.temp['address'].push(streetData)
                areaText += ' / ' + streetData.name
              }
            } else if (data[key]) this.temp[key] = data[key]
          }
          this.rowData = data
          // 北京 / 北京市 / 东城区 / 东华门街道;
          this.$refs['cascaderRef'].inputValue = areaText
        }
      },
      success() {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) return
          this.$confirm('确认保存客户信息？', '操作提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.submit(this.type)
            })
            .catch(() => {})
        })
      },
      async submit(type) {
        const params = {
          isPickUp: 1,
          isMain: this.rowData.isMain,
          csmPickupId: this.rowData.csmPickupId || undefined,
          csmId: this.rowData.csmId || undefined,
          csmRgPhoneId: this.rowData.csmRgPhoneId || undefined,
          csmRgAddressId: this.rowData.csmRgAddressId || undefined
        }
        for (const key in this.temp) {
          params[key] = this.temp[key]
        }
        this.temp['address'].forEach((v, i) => {
          switch (i) {
          case 0:
            params.provinceName = v.name
            params.provinceCode = v.code
            break
          case 1:
            params.cityName = v.name
            params.cityCode = v.code
            break
          case 2:
            params.countryName = v.name
            params.countryCode = v.code
            break
          case 3:
            params.streetName = v.name
            params.streetCode = v.code
            break
          }
        })

        const { status } = await pickUpCustomerSava(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `${type === 1 ? '新增' : '更新'}成功"`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.reset()
        }
      },

      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
        this.orgId = value.orgId
        this.orgName = value.orgName
      },
      reset() {
        this.type = 1
        this.$refs.dataForm.resetFields()
        this.rowData = {
          csmId: ''
        }
        this.isShow = false
      },
      async getCsmCode() {
        const { status, data } = await getCodeNum({ type: 2 })
        if (status === 200) {
          this.temp.csmCode = data
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
